import React from 'react';
import './DepAndStaffDepSet.css'
import {Button, Tree, Modal, Input, Select, message} from "antd";
import { PlusOutlined, EditOutlined, DeleteOutlined, }from '@ant-design/icons';
// import axios from 'axios';
import axios from '../../util/http'
import * as url from '../../util/api'

const { Option } = Select;

class DepAndStaffDepSet extends React.Component {
    constructor(props){
        super(props);
        this.state={
            allDept:[],   //全部部门数据（用于渲染下拉列表）
            DepData: [   //部门数据（树形控件数据）
                /*{
                    title:<div className='treeNodeRow'>
                        <span>parent 1</span>
                        <div className='treeBtnBox'>
                            <Button><PlusOutlined style={{color:'#13c19f'}}/>增加子部门</Button>
                            <Button><EditOutlined  style={{color:'#13c19f'}}/>修改</Button>
                            <Button><DeleteOutlined  style={{color:'#13c19f'}}/>删除</Button>
                        </div>
                    </div>,
                    key: '1',
                    children: [
                        {title: 'leaf', key: '1-1',},
                        {title: 'leaf', key: '1-2',},
                    ],
                },
                {
                    title: 'parent 2',
                    key: '2',
                    children: [
                        {title: 'leaf', key: '2-1',},
                        {title: 'leaf', key: '2-2',},
                        {
                            title: 'leaf',
                            key: '2-2-1',
                            children: [
                                {title: 'leaf', key: '2-2-1-1',},
                                {title: 'leaf', key: '2-2-1-t2',},
                            ],
                        },
                    ],
                },
                {
                    title: 'parent 3',
                    key: '3',
                    children: [
                        {title: 'leaf', key: '3-1',},
                        {title: 'leaf', key: '3-2',},
                    ],
                },*/
            ],

            addDepModalVisible:false,   //新增 部门 的模态框显示状态
            addDepInfo:{deptName:''},    //新增的 部门

            addSonDepModalVisible:false,   //新增子部门 / 修改 的模态框显示状态
            addSonDepInfo:{   //新增/修改的 子部门
                deptName:'',    //子部门名称
                deptParentName:'',    //父级部门名称
            },
            modalFor:'addSon',   //当前模态框的作用（新增子部门addSon/新增根部门addRoot/修改edit）
            deleteModalVisible:false,   //删除部门模态框状态
            toDeleteDeptData:{},   //要删除的部门数据
            tiShiModalVisible:false,   //确认提交提示框状态

        }
    }
    /*--------------------公用--------------------*/
    //改变state
    changeState=(name,value)=>{
        this.setState({
            [name]:value
        })
    };
    //发起请求，获取部门信息
    getDeptInfo=()=>{
        axios({
            url:url.showDeptInfo,
            method:'post',
            data:'',
        }).then(res=>{
            // console.log('获取部门信息');
            // console.log(res);
            if (res.data.code===200){
                // message.success('部门信息获取成功');
                //转换树形
                this.toTreeData(res.data.data);
                res.data.data.forEach((item,index)=>{
                    item.key=index;
                });
                //将数据存入state
                this.changeState('allDept',res.data.data);  //存起来，用于渲染下拉列表
            }else {
                message.error('部门信息获取失败');
            }
        })
    };
    //对将部门信息转为树形
    toTreeData=(data)=>{
        let newData=[];
        data.forEach((item,index)=>{
            item.key=index;
            item.title=this.showBtn(item);
            if (item.deptParentId==='0'&&item.deptName!=='根部门'){  //如果是根类别下的部门
                item.children=this.addChildren(item.deptId,data);
                newData.push(item);
            }
        });
        // console.log(newData);
        //将数据存入state
        this.changeState('DepData',newData);
    };
    //用于子部门自循环添加树形
    addChildren=(parentId,data)=>{
        let newChildrenData=[];
        data.forEach(item=>{
            if (item.deptParentId===parentId){
                newChildrenData.push(item);
            }
        });
        newChildrenData.forEach(item=>{
            let smallChildren = this.addChildren(item.deptId,data);
            if (smallChildren.length>0){
                item.children=smallChildren;
            }
        });
        return newChildrenData;
    };

    //手动渲染按钮
    showBtn=(info)=>{
        return <div className='treeNodeRow'>
            <span>{info.deptName}</span>
            <div className='treeBtnBox'>
                <Button onClick={()=>this.addSonDeptBtn(info)}><PlusOutlined style={{color:'#13c19f'}}/>增加子部门</Button>
                <Button onClick={()=>this.editDeptBtn(info)}><EditOutlined  style={{color:'#13c19f'}}/>修改</Button>
                <Button onClick={()=>this.deleteBtn(info)}><DeleteOutlined  style={{color:'#13c19f'}}/>删除</Button>
            </div>
        </div>
    };
    //发起请求删除部门
    deleteDept=()=>{
        axios({
            url:url.deleteDept,
            method:'post',
            data:this.state.toDeleteDeptData,
        }).then(res=>{
            // console.log(res);
            if (res.data.code===200){
                message.success('删除成功');
                this.getDeptInfo();  //刷新页面
            }else {
                message.error('删除失败，该部门下有子部门或员工');
            }
        })
    };
    //发起请求新增部门（根部门）
    toAddDept=()=>{
        // console.log(this.state.addDepInfo);
        axios({
            url:url.addRootDept,
            method:'post',
            data:this.state.addDepInfo,
        }).then(res=>{
            // console.log(res);
            if (res.data.code===200){
                message.success('新增成功');
                this.changeState('addDepModalVisible',false);   //关闭新增弹窗
                this.getDeptInfo();  //刷新页面
            }else {
                message.error('新增失败');
            }
        })
    };
    //发起请求新增部门（子部门）
    toAddSonDept=()=>{
        // console.log(this.state.addSonDepInfo);
        axios({
            url:url.addSonDept+`?deptName=${this.state.addSonDepInfo.deptName}&&deptParentName=${this.state.addSonDepInfo.deptParentName}`,
            method:'post',
            data:this.state.addSonDepInfo,
        }).then(res=>{
            // console.log(res);
            if (res.data.code===200){
                message.success('新增成功');
                this.changeState('addSonDepModalVisible',false);   //关闭新增弹窗
                this.getDeptInfo();  //刷新页面
            }else {
                message.error('新增失败');
            }
        })
    };
    //发起请求修改部门
    toEditDept=()=>{
        let postData={
            deptId:this.state.addSonDepInfo.deptId,
            deptName:this.state.addSonDepInfo.deptName,
            deptParentName:this.state.addSonDepInfo.deptParentName,
        };
        // console.log(postData);
        axios({
            url:url.editDept+`?deptId=${postData.deptId}&&deptName=${postData.deptName}&&deptParentName=${postData.deptParentName}`,
            method:'post',
            data:postData,
        }).then(res=>{
            // console.log(res);
            if (res.data.code===200){
                message.success('修改成功');
                this.changeState('addSonDepModalVisible',false);   //关闭新增弹窗
                this.getDeptInfo();  //刷新页面
            }else {
                message.error('修改失败');
            }
        })
    };
    /*--------------------新增 部门 --------------------*/
    //点击‘新增部门’
    addDeptBtn=()=>{
        this.changeState('modalFor','addRoot');
        this.changeState('addDepModalVisible',true);
    };
    //点击模态框中'确认'
    toAddDep = e => {
        this.changeState('tiShiModalVisible',true);   //打开提示框
    };
    //点击模态框中'取消'
    AddDepCancel = e => {
        this.changeState('addDepModalVisible',false)
    };
    //输入框的值发生改变
    addDepTextChange=(itemName)=>{
        return (e)=>{
            this.changeState('addDepInfo',{[itemName]:e.target.value});
        }
    };
    /*--------------------新增 子部门 / 修改 --------------------*/
    //点击‘新增子部门’
    addSonDeptBtn=(info)=>{
        this.changeState('modalFor','addSon');
        this.changeState('addSonDepInfo',{deptName:'', deptParentName:info.deptName,});  //清空数据
        this.changeState('addSonDepModalVisible',true)
    };
    //点击模态框中'确认'
    toAddSonDep = () => {
        this.changeState('tiShiModalVisible',true);   //打开提示框
    };
    //点击模态框中'取消'
    AddSonDepCancel = e => {
        this.changeState('addSonDepModalVisible',false);
        this.changeState('addSonDepInfo',{deptName:'', deptParentName:'',});  //清空数据
    };
    //渲染下拉列表
    showDeptOption=()=>{
        let dom=[];
        this.state.allDept.forEach(item=>{
            dom.push(<Option key={item.deptName}>{item.deptName}</Option>)
        });
        return dom;
    };
    //输入框的值发生改变
    addSonTextChange=(itemName)=>{
        return (e)=>{
            let newAddSonDepInfo=Object.assign(this.state.addSonDepInfo,{[itemName]:e.target.value});
            this.changeState('addSonDepInfo',newAddSonDepInfo);
        }
    };
    //部门的下拉列表值改变
    selectChange=(value)=>{
        let newAddSonDepInfo=Object.assign(this.state.addSonDepInfo,{deptParentName:value});
        this.changeState('addSonDepInfo',newAddSonDepInfo);
    };
    /*--------------------树节点按钮--------------------*/
    //修改部门按钮
    editDeptBtn=(info)=>{
        this.changeState('modalFor','edit');  //修改状态
        let upData={deptId:info.deptId,deptName:info.deptName, deptParentName:'',};
        if (info.deptParentId!=='0'){   //如果有父部门
            this.state.allDept.forEach(item=>{
                if (info.deptParentId===item.deptId){   //找父部门名称
                    upData.deptParentName=item.deptName;
                }
            });
        }else {
            upData.deptParentName='根部门'
        }
        // console.log(upData);
        this.changeState('addSonDepInfo',upData);  //传入
        this.changeState('addSonDepModalVisible',true)
    };
    //点击删除按钮
    deleteBtn=(info)=>{
        let newInfo = {
          deptId:info.deptId,
          deptName:info.deptName,
        };
        this.changeState('toDeleteDeptData',newInfo);
        this.changeState('deleteModalVisible',true);
    };
    //点击删除提示框“确定”
    toDeleteDept=()=>{
        this.deleteDept();  //发起删除请求
        this.changeState('deleteModalVisible',false);
    };
    //点击删除提示框“取消”
    toCloseModal=()=>{
        this.changeState('deleteModalVisible',false);
    };
    /*--------------------提交提示框--------------------*/
    //提交提示框，点击确认
    toSubmitDept=()=>{
        if (this.state.modalFor==='addRoot'){   //如果是新增根部门
            this.changeState('tiShiModalVisible',false);   //关闭提示框
            this.toAddDept();
        }else if (this.state.modalFor==='addSon'){   //如果是新增子部门
            this.changeState('tiShiModalVisible',false);   //关闭提示框
            this.toAddSonDept();
        }else if (this.state.modalFor==='edit'){   //如果是修改部门
            this.changeState('tiShiModalVisible',false);   //关闭提示框
            this.toEditDept();
        }
    };
    //提交提示框，点击取消
    toCloseTiShiModal=()=>{
        this.changeState('tiShiModalVisible',false);
    };

    render() {
        return (
            <div className='DepAndStaffDepSetPage'>
                <div className='hang1'>
                    <Button type="primary" onClick={this.addDeptBtn}>新增部门</Button>
                </div>
                {/*树状展示部门*/}
                <div className='treeBox'>
                    <Tree
                        className="draggable-tree"
                        defaultExpandedKeys={this.state.expandedKeys}     //默认展开
                        treeData={this.state.DepData}   //数据
                    />
                </div>
                {/*新增部门模态框*/}
                <Modal
                    title="新增部门"
                    visible={this.state.addDepModalVisible}
                    onOk={this.toAddDep}
                    onCancel={this.AddDepCancel}
                    okText='确认'
                    cancelText='取消'
                    getContainer={()=>document.getElementsByClassName('DepAndStaffDepSetPage')[0]}
                    destroyOnClose={true}  /*关闭时销毁*/
                >
                    <form>
                        <table>
                            <tbody>
                                <tr>
                                    <td>部门名称</td>
                                    <td>
                                        <Input onChange={this.addDepTextChange('deptName')} placeholder='请输入部门名称' value={this.state.addDepInfo.deptName}/>
                                    </td>
                                </tr>
                                <tr>
                                    <td>上级部门</td>
                                    <td>
                                        <Select defaultValue='根部门' onChange={this.selectChange} disabled/>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </form>
                </Modal>
                {/*新增子部门/修改模态框*/}
                <Modal
                    title="部门信息"
                    visible={this.state.addSonDepModalVisible}
                    onOk={this.toAddSonDep}
                    onCancel={this.AddSonDepCancel}
                    okText='确认'
                    cancelText='取消'
                    getContainer={()=>document.getElementsByClassName('DepAndStaffDepSetPage')[0]}
                    destroyOnClose={true}  /*关闭时销毁*/
                >
                    <form>
                        <table>
                            <tbody>
                            <tr>
                                <td>部门名称</td>
                                <td>
                                    <Input onChange={this.addSonTextChange('deptName')} placeholder='请输入部门名称' value={this.state.addSonDepInfo.deptName}/>
                                </td>
                            </tr>
                            <tr>
                                <td>上级部门</td>
                                <td>
                                    <Select defaultValue={this.state.addSonDepInfo.deptParentName} onChange={this.selectChange}>
                                        {this.showDeptOption()}
                                    </Select>
                                </td>
                            </tr>
                            </tbody>
                        </table>
                    </form>
                </Modal>
                {/*确认删除模态框*/}
                <Modal
                    title="提示"
                    visible={this.state.deleteModalVisible}
                    onOk={this.toDeleteDept}
                    onCancel={this.toCloseModal}
                    okText="确认"
                    cancelText="取消"
                    getContainer={()=>document.getElementsByClassName('DepAndStaffDepSetPage')[0]}
                    destroyOnClose={true}  /*关闭时销毁*/
                >
                    <h1 style={{fontSize:'18px'}}>确认删除该部门？</h1>
                </Modal>
                {/*确认提交模态框*/}
                <Modal
                    title="提示"
                    visible={this.state.tiShiModalVisible}
                    onOk={this.toSubmitDept}
                    onCancel={this.toCloseTiShiModal}
                    okText="确认"
                    cancelText="取消"
                    getContainer={()=>document.getElementsByClassName('DepAndStaffDepSetPage')[0]}
                    destroyOnClose={true}  /*关闭时销毁*/
                    style={{zIndex:99}}
                >
                    <h1 style={{fontSize:'18px'}}>确认提交？</h1>
                </Modal>
            </div>
        );
    };
    componentDidMount() {
        //获取部门信息
        this.getDeptInfo();
    }
}

export default DepAndStaffDepSet;